#!/usr/bin/env python3
# vim: tabstop=4 expandtab

import datetime
from os import getenv
from pathlib import Path

from gemini_antenna.db import AntennaDB
from gemini_antenna.URLHelper import URLHelper

def app() -> None:
    def log(msg) -> None:
        timestamp = datetime.datetime.utcnow().isoformat()
        with open(dataroot / "antenna.log", "a") as logfile:
            print(timestamp, msg, file=logfile)

    def printInvalidURL(feedurl: str) -> None:
        log(f"ERROR: pretty sure '{feedurl}' is not a real URL...")
        print("20 text/gemini", end="\r\n")
        print("Error adding feed.", end="\n\n")
        print("Feed URL is not valid.")

    def printIsBlocked(feedurl: str) -> None:
        log(f"ERROR: feed URL '{feedurl}' is blocked by rules.")
        print("20 text/gemini", end="\r\n")
        print("Error adding feed.", end="\n\n")
        print("Feed URL is blocked by instance rules.")

    dataroot = Path(getenv('ANTENNA_DATAROOT', default=str(Path.cwd())))
    feedurl = getenv('QUERY_STRING')
    db = AntennaDB(dataroot / "antenna.sqlite")
    uh = URLHelper(dataroot / "blocklist.txt")

    if not feedurl:
        print("10 Feed URL:", end="\r\n")
        return

    try:
        feedurl = uh.resolve(feedurl)
    except ValueError:
        printInvalidURL(feedurl)
        return

    if not uh.mightBeAURL(feedurl):
        printInvalidURL(feedurl)
        return

    if uh.isBlocked(feedurl):
        printIsBlocked(feedurl)
        return

    db.queueFeed(feedurl)
    log(f"INFO: Feed '{feedurl}' added to queue.")

    print("20 text/gemini", end="\r\n")
    print("Thank you for your submission!", end="\n\n")
    print("This feed will be processed in a few minutes.")

def main() -> None:
    # TODO: handle exceptions
    app()

if __name__ == "__main__":
    main()
